/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-17
 * Time: 15:59
 */
public class Sort {
    //归并排序_非递归实现
    public static void mergeSortNor(int[] arr) {
        //子序列的长度设置
        int gap = 1;

        //这层循环控制gap的增长
        while (gap < arr.length) {
            //这层循环控制子序列的合并,每次处理两个相邻的子序列，因此i+2*gap
            for (int i = 0; i < arr.length; i += 2*gap) {
                //左子序列起始
                int left = i;
                //左子序列结束
                int mid = left + gap - 1;
                //防止越界
                if (mid >= arr.length) {
                    mid = arr.length - 1;
                }

                //右子序列结束
                int right = mid + gap;
                //防止越界
                if (right >= arr.length) {
                    right = arr.length-1;
                }

                //开始合并
                merge(arr,left,mid,right);
            }
            gap *= 2;
        }
    }
    //合并
    private static void merge(int[] arr,int left,int mid,int right) {
        int[] tmp = new int[right - left + 1];
        int k = 0;

        int s1 =  left;
        int e1 = mid;

        int s2 = mid+1;
        int e2 = right;

        while (s1 <= e1 && s2 <= e2) {
            if (arr[s1] < arr[s2]) {
                tmp[k++] = arr[s1++];
            }else {
                tmp[k++] = arr[s2++];
            }
        }

        while (s1 <= e1) {
            tmp[k++] = arr[s1++];
        }

        while (s2 <= e2) {
            tmp[k++] = arr[s2++];
        }

        for (int i = 0; i < k; i++) {
            arr[i + left] = tmp[i];
        }
    }
}
